<template>
	<view class="content">
		<button @click="search">开始搜索</button>
		<div>
			当前已连接设备:{{curConnectDevice.name}}
			<button @click="sendWifi">配网</button>
		</div>
		<p v-for="(item,index) in discouverBleDeviesList" :key="item.deviceId" class="deviceItem">
			{{item.name}}

		<div style="display: flex;">
			<button @click="connect(item)">连接</button>

		</div>
		</p>

	</view>
</template>

<script setup>
	import {
		watch,
		watchEffect,
		ref,
		getCurrentInstance,
		inject
	} from 'vue';
	let BleBT = inject('BleBT')
	console.log(BleBT)
	BleBT.initBleBT()

	function search() {
		BleBT.discoverBT()
	}

	//保存附近蓝牙设备列表
	let discouverBleDeviesList = ref([])

	//监听BleBT 插件发出得各类蓝牙事件
	uni.$on('onBleBTMsg', (payload) => {
		switch (payload.EventType) {
			//用户手机蓝牙状态变化 例如蓝牙适配器状态变化或搜索状态变化 
			case 'BTStateChange':
				break;

				//监听打开蓝牙搜索成功搜索到附近蓝牙得事件
			case 'BleBTFound':
				discouverBleDeviesList.value = [...payload.allFoundDevices]
				break;

				//已连接蓝牙设备状态得变化 例如是成功连接还是异常中断
			case 'BleDeviceConnectStateChange':
				break;

				//监听已连接的蓝牙设备值得变化
			case 'BleConnectDeviceValueChange':
				break;
			default:
				break;
		}
	})


	let curConnectDevice = ref({})

	function connect(device) {
		BleBT.connectBleBT(device).then(res => {
			curConnectDevice.value = BleBT.curConnectBTDevice
			console.log(curConnectDevice.value)
		})
	}

	async function sendWifi() {
		let wifiInfo = {
			method: "WiFiConnect",
			value: `Xiaomi_A65A;@1234567;coderxq5115c9b7;coderxq;coderxq5115c9b7_0bab01;a7e64d8f;http://test-api.nexis.ifi-cloud.com/api/device/gen/activate;http://test-api.nexis.ifi-cloud.com/api/auth/passport;http://test-api.nexis.ifi-cloud.com/api/ntk/rq/configuration`
		}
		let bufferData = string2arrayBuffer(JSON.stringify(wifiInfo))

		//给已连接得蓝牙设备发送bufferData数据 
		BleBT.sendDataToBleBT(bufferData).then(res => {

		})

	}

	/**
	 * string 转 arrayBuffer
	 * @param {Object} str
	 */
	function string2arrayBuffer(str) {
		var bytes = new Array();
		var len, c;
		len = str.length;
		for (var i = 0; i < len; i++) {
			c = str.charCodeAt(i);
			if (c >= 0x010000 && c <= 0x10FFFF) {
				bytes.push(((c >> 18) & 0x07) | 0xF0);
				bytes.push(((c >> 12) & 0x3F) | 0x80);
				bytes.push(((c >> 6) & 0x3F) | 0x80);
				bytes.push((c & 0x3F) | 0x80);
			} else if (c >= 0x000800 && c <= 0x00FFFF) {
				bytes.push(((c >> 12) & 0x0F) | 0xE0);
				bytes.push(((c >> 6) & 0x3F) | 0x80);
				bytes.push((c & 0x3F) | 0x80);
			} else if (c >= 0x000080 && c <= 0x0007FF) {
				bytes.push(((c >> 6) & 0x1F) | 0xC0);
				bytes.push((c & 0x3F) | 0x80);
			} else {
				bytes.push(c & 0xFF);
			}
		}
		var array = new Int8Array(bytes.length);
		for (var i in bytes) {
			array[i] = bytes[i];
		}
		return array.buffer;
	}
</script>

<style>
	.deviceItem {
		padding: 10px 15px;
		display: flex;
		justify-content: space-between;
	}
</style>